

module.exports = (function () {
	var mysql = require("mysql");
	var config = {
		useTable: "USE csblog",
		creatDBSql: "CREATE DATABASE csblog"
	}
	function connectDB(fn) {
		var connection = mysql.createConnection({
			host: "localhost",
			user: "root",
			password: "jinchao233.com"
		});
		var promise = new Promise(function (resolve, reject) {
			connection.connect(function (err) {
				err ? reject(err) : resolve()
			})
		});
		promise
			.then(queryTable,function (err) {
				console.log("connnect sql err: "+err.stack);
			})

			.then(function (response) {}, createDataBase)

			.then(queryTable,function (err) {})

		function queryTable() {
			return new Promise(function (resolve, reject) {
				connection.query(config.useTable, function (err,result) {
					err ? reject(err) : (resolve(result),fn(connection,result));
				})
			})
		}
		function createDataBase() {
			return new Promise(function (resolve, reject) {
				connection.query(config.creatDBSql, function (err, result) {
					err ? reject(err) : (resolve(result),fn(connection,result));
				})
			})
		}
		
		// connection.connect(function (err) {
		// 	if (err) {
		// 		console.log("connnect sql err: "+err.stack);
		// 		return;
		// 	}
		// 	var con_database = "USE csblog";
		// 	connection.query(con_database,function (err,result) {
		// 		if (err) {
		// 			console.log("query users err:")
		// 			var create_db = "CREATE DATABASE csblog";
		// 			connection.query(create_db, function (err, result) {
		// 				if (err) {
		// 					console.log(err);
		// 					return;
		// 				}
		// 				connection.query(con_database, function (err, result) {
		// 					if (err) {
		// 						console.log(err);
		// 						return;
		// 					}
		// 					console.log("connent csblog db success");
		// 					fn(connection,result);
		// 				})
		// 			});
		// 			return;
		// 		}
		// 		console.log("connent csblog db success");
		// 		fn(connection,result);

		// 	});
		// 	console.log("connect success: "+connection.threadId)
		// });
	}
	return {
		connectDB: connectDB
	}
})();